--#!/usr/bin/lua
-- Gemline DEMO 
-- USE: <margin> gemtext files
render = require( "gemline" )
links = {}
lines = {}
pages = {}
margin = 66

function loadPages( len )
   len = len or margin
   pages[#pages+1] = 1
   local l = 0
   for line, rows in pairs( lines ) do
      if l + #rows > len then
         pages[#pages+1] = line
         l = #rows
      else
         if string.sub( rows[1], 1, 2 ) == "--" then --commento
            if string.sub( rows[1], 3, 3 ) == "-" and
               line < #lines
            then -- new page
               pages[#pages+1] = line + 1
               l = #rows
            end
         else
            l = l + #rows
         end
      end
   end
end

function printPages( first, last )
   first = first or 1
   if first > #pages then first = #pages end
   last = last or first
   if type( last ) == "boolean" then last = #pages end
   for page = first, last do
      if page == #pages then
         lastLine = #lines
      else
         lastLine = pages[page+1]-1
      end
      io.write( "\27[H\27[2J" ) -- ERASE SCREEN
      local l = 0
      for line = pages[page], lastLine do
         local rows = lines[line]
         if string.sub( rows[1], 1, 2 ) ~= "--" then --commento
            for n, row in pairs( rows ) do
               io.write( row )
            end
         end
      end
      io.write( "\nPage ", page, " of ", #pages, "\n" )
   end
end
 
if #arg == 0 then
   for line in io.lines( "gemline.gmi" ) do
      lines[#lines+1] = render( line, margin )
   end
   loadPages( margin )
   printPages( 1, true)
   print()
else
   for a = 1, #arg do
      if tonumber( arg[a] ) then
         margin = tonumber( arg[a] )
         -- 1/1= 74, 2/3=51, 1/2=38 e 1/3=27
         if margin > 74 then margin = 74 end
         if margin < 27 then margin = 27 end
         print( "\nRight margin: "..margin )
      else
         lines = {}
         print()
         for line in io.lines( arg[a] ) do
            lines[#lines+1] = render( line, margin )
         end
         loadPages( margin )
         local page = 1
         while true do
            printPages( page )
            io.write("Return cicle pages or cmd q quit > ")
            cmd = io.read()
            if string.lower(cmd) == "q" then
               io.write("Bye!\n")
               break
            end
            if page == #pages then page = 1 else page = page + 1 end
         end
      end
   end
end
